package com.example.zsr.downloadcontinue;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.zsr.downloadcontinue.ToolUtils.FileInfo;
import com.example.zsr.downloadcontinue.ToolUtils.ThreadInfo;
import com.example.zsr.downloadcontinue.db.DBThreadListenerImp;
import com.example.zsr.downloadcontinue.db.DBThreadListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by zhengshaorui on 2017/2/22.
 */

public class DownloadTask {
    private static final String TAG = "zsr";
    private Context mContext;
    private int downloadlength = 0;
    private FileInfo mFileInfo;
    public static boolean isPause = false;

    private DBThreadListener mDbThreadListener;
    public DownloadTask(Context mContext) {
        this.mContext = mContext;
        mDbThreadListener = new DBThreadListenerImp(mContext);
    }

    public void download(FileInfo fileInfo){
        mFileInfo = fileInfo;
        List<ThreadInfo> threadInfos = mDbThreadListener.getThreads(fileInfo.getApkurl());
        ThreadInfo mThreadInfo;
        if (threadInfos.size() == 0){
            mThreadInfo = new ThreadInfo(0,fileInfo.getApkurl(),0,fileInfo.getLength(),0,fileInfo.getLength());
        }else{
            mThreadInfo = threadInfos.get(0);
        }
        new DownloadThread(mThreadInfo).start();
    }

    class DownloadThread extends Thread{
        ThreadInfo mThreadInfo;

        public DownloadThread(ThreadInfo threadinfo) {
            this.mThreadInfo = threadinfo;
        }

        @Override
        public void run() {
            super.run();
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            BufferedInputStream bis = null;
            //开始之前先检测是否数据库有线程信息
            if (!mDbThreadListener.isThreadExsits(mThreadInfo.getUrl(),mThreadInfo.getId())){
                mDbThreadListener.insertThread(mThreadInfo); //没有则把线程信息保存进去
            }
            try {
                URL url = new URL(mThreadInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                //加上这句是为了防止connection.getContentLength()获取不到
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);


                //设置下载位置
                int start = mThreadInfo.getStart()+mThreadInfo.getFinished(); //起始位置
                int end = mThreadInfo.getEnd(); //结束位置
                conn.setRequestProperty("Range", "bytes="+start+"-"+end);


                //文件写入位置
                File file = new File(mFileInfo.getDir(),mFileInfo.getFileName());
                raf = new RandomAccessFile(file,"rwd");
                raf.seek(start);

                downloadlength += mThreadInfo.getFinished(); //主要是暂停之后，重新下载，获取以前的进度



                int len = -1;
                byte[] bytes = new byte[1024*2];
                bis = new BufferedInputStream(conn.getInputStream());
                Intent progresslIntent = new Intent("com.msg.apk_install_progress");
                while( (len = bis.read(bytes)) != -1 ){
                    raf.write(bytes,0,len);
                    downloadlength += len;
                    if (isPause) {
                        //数据库保存当前信息
                        mDbThreadListener.updateThread(mThreadInfo.getUrl(), mThreadInfo.getId(),
                                downloadlength);
                        return;
                    }
                    progresslIntent.putExtra("progress",downloadlength*100/mFileInfo.getLength());
                    mContext.sendBroadcast(progresslIntent);

                    //以百分比的形式传递
                    Log.d(TAG, "run: "+downloadlength*100/mFileInfo.getLength());
                }

                //如果完成，则把以前的线程信息干掉
                mDbThreadListener.deleteThread(mThreadInfo.getUrl(),mThreadInfo.getId());

            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "downloaderror: "+e.toString());
            }finally {
                if (bis != null) try {
                    bis.close();
                    if (raf != null) raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (conn != null) conn.disconnect();
            }

        }
    }
}
